#define _CRT_SECURE_NO_WARNINGS 1
#include<iostream>
#include<cstring>
using namespace std;
const int N = 10;
int n = 5;
int a[N];
int b[N];
int calc(int x)
{
    int f = 0;
    while (x)
    {
        f++;
        x &= (x - 1);
    }
    return f;
}
int main()
{
    int r;
    cin >> r;
    while (r--)
    {
        memset(a, 0, sizeof(a));
        for (int i = 0; i < n; i++)
        {
            for (int j = 0; j < n; j++)
            {
                char k;
                cin >> k;
                if (k == '0')
                    a[i] |= 1 << j;
            }
        }
        int ret = 0x3f3f3f3f;
        for (int i = 0; i < (1 << n); i++)
        {
            int push = i;
            int cnt = 0;
            memcpy(b, a, sizeof(a));
            for (int j = 0; j < n; j++)
            {
                cnt += calc(push);
                b[j] = b[j] ^ push ^ (push << 1) ^ (push >> 1);
                b[j] &= (1 << n) - 1;
                b[j + 1] ^= push;
                push = b[j];
            }
            if (b[n - 1] == 0)
                ret = min(ret, cnt);
        }
        if (ret <= 6)
        {
            cout << ret << endl;
        }
        else
        {
            cout << -1 << endl;
        }
    }
    return 0;
}